package cn.zb.index;

import cn.zb.common.BaseController;
import cn.zb.user.User;
import cn.zb.utils.DateUtil;
import cn.zb.utils.weibo4j.Users;
import com.qq.connect.oauth.Oauth;
import cn.zb.utils.weibo4j.model.WeiboException;
import cn.zb.utils.weibo4j.util.BareBonesBrowserLaunch;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * IndexController
 */
public class IndexController extends BaseController {
	public void index() {
        render("index.vm");
    }

    public void signout() {
        if(getRequest().getSession().getAttribute(ZB_ADMIN_USER) != null) {
            getRequest().getSession().removeAttribute(ZB_ADMIN_USER);
        }
        redirect("/");
    }

    public void qqlogin() throws QQConnectException {
        redirect(new Oauth().getAuthorizeURL(getRequest()));
    }

    public void qqlogincallback() throws IOException, QQConnectException {
        HttpServletRequest request = getRequest();
        AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
        String accessToken = null,openID = null;
        long tokenExpireIn = 0L;
        if (accessTokenObj.getAccessToken().equals("")) {
            setAttr("error", "用户取消了授权或没有获取到响应参数");
            render("index.vm");
        } else {
            accessToken = accessTokenObj.getAccessToken();
            tokenExpireIn = accessTokenObj.getExpireIn();
            // 利用获取到的accessToken 去获取当前用的openid -------- start
            OpenID openIDObj =  new OpenID(accessToken);
            openID = openIDObj.getUserOpenID();
            User user = User.me.findByOpenId(openID, "qq");
            if (user == null) {
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                if (userInfoBean.getRet() == 0) {
                    String nickname = userInfoBean.getNickname();
                    String gender = userInfoBean.getGender();
                    String avatar = userInfoBean.getAvatar().getAvatarURL50();
                    Date expire_in = DateUtil.getDateAfter(new Date(), (int) tokenExpireIn / 60 / 60 / 24);
                    getModel(User.class).set("nickname", nickname)
                            .set("gender", gender)
                            .set("avatar", avatar)
                            .set("access_token", accessToken)
                            .set("openid", openID)
                            .set("expires_in", expire_in)
                            .set("third_name", "qq").save();
                    user = User.me.findByOpenId(openID, "qq");
                } else {
                    setAttr("error", "很抱歉，我们没能正确获取到您的信息，原因是： " + userInfoBean.getMsg());
                    render("index.vm");
                }
            } else if(DateUtil.isExpire((Date) user.get("expires_in"))) {
                user.set("expire_in", tokenExpireIn).set("openid", openID).update();
            }
            setSessionAttr(ZB_ADMIN_USER, user);
            redirect("/record");
        }
    }

    public void weibologin() throws WeiboException, IOException {
        cn.zb.utils.weibo4j.Oauth oauth = new cn.zb.utils.weibo4j.Oauth();
        redirect(oauth.authorize("code"));
    }

    public void weibologincallback() throws WeiboException {
        String code = getPara("code");
        cn.zb.utils.weibo4j.Oauth oauth = new cn.zb.utils.weibo4j.Oauth();
        cn.zb.utils.weibo4j.http.AccessToken accessToken = oauth.getAccessTokenByCode(code);
        User user = User.me.findByOpenId(accessToken.getUid(), "sina");
        Integer expireIn = Integer.parseInt(accessToken.getExpireIn());
        Users users = new Users(accessToken.getAccessToken());
        cn.zb.utils.weibo4j.model.User user1 = users.showUserById(accessToken.getUid());
        String nickname = user1.getName();
        String gender = user1.getGender();
        if (gender.equals("m")) gender = "男";
        else if (gender.equals("f")) gender = "女";
        else if (gender.equals("n")) gender = "未知";
        String avatar = user1.getavatarLarge();
        Date expire_in = DateUtil.getDateAfter(new Date(), expireIn / 60 / 60 / 24);
        if(user == null) {
            getModel(User.class).set("nickname", nickname)
                    .set("gender", gender)
                    .set("avatar", avatar)
                    .set("access_token", accessToken.getAccessToken())
                    .set("openid", accessToken.getUid())
                    .set("expires_in", expire_in)
                    .set("third_name", "sina").save();
            user = User.me.findByOpenId(accessToken.getUid(), "sina");
        } else if(DateUtil.isExpire((Date) user.get("expires_in"))) {
            user.set("expire_in", expire_in)
                    .set("access_token", accessToken.getAccessToken()).update();
        }
        setSessionAttr(ZB_ADMIN_USER, user);
        redirect("/record");
    }

}